<template>
  <div class="p-4">
    <el-card class="box-card">
      <div slot="header" class="clearfix flex justify-between">
        <el-form class="flex-grow" inline>
          <el-form-item>
            <el-button
              icon="el-icon-plus"
              type="success"
              @click="deBounceWrap(handleAdd)"
            >新增
            </el-button
            >
            <el-button
              icon="el-icon-delete"
              type="danger"
              @click="deBounceWrap(handleDelAll)"
            >批量删除
            </el-button
            >
          </el-form-item>
        </el-form>

        <div class="flex-grow-0">
          <el-select
            v-model="listQuery.sale_status"
            clearable
            placeholder="请选择销售状态"
          >
            <el-option label="上架" value="1"></el-option>
            <el-option label="下架" value="0"></el-option>
          </el-select>
          <el-input
            v-model="listQuery.gift_name"
            class="ml-2"
            clearable
            placeholder="请输入礼物名称"
            style="width:35%"
          ></el-input>
          <el-button
            class="el-icon-search p-1 text-white text-2xl bg-green-500 cursor-pointer"
            type="primary"
            @click="getList"
          >搜索
          </el-button
          >
        </div>
      </div>

      <el-table :data="data" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" prop="id" width="150px"></el-table-column>
        <el-table-column label="套装名称" prop="name"></el-table-column>
        <el-table-column label="套装说明" prop="desc"></el-table-column>
        <el-table-column label="套装图片" prop="picture">
          <template slot-scope="{ row }">
            <el-popover max-width="420" placement="right" trigger="hover">
              <img
                :src="row.picture"
                alt=""
                style="max-width: 200px; max-height: 200px"
              />
              <img
                slot="reference"
                :src="row.picture"
                alt=""
                style="width: 50px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="套装状态" prop="sold">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sold === 1" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort"></el-table-column>
        <el-table-column label="添加时间" prop="created_at"></el-table-column>
        <el-table-column label="操作" width="320px">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              plain
              size="mini"
              type="primary"
              @click="deBounceWrap(handleEdit, scope.row)"
            >编辑
            </el-button
            >
            <el-button
              icon="el-icon-notebook-2"
              plain
              size="mini"
              type="warning"
              @click="deBounceWrap(handleDetails, scope.row)"
            >套装详情
            </el-button
            >

            <el-dropdown style="margin-left: 10px" trigger="click">
              <el-button type="primary"
              >操作<i class="el-icon-arrow-down el-icon--right"></i
              ></el-button>

              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-if="scope.row.sold === 1"
                  @click.native="deBounceWrap(handleStatus, scope.row)"
                >不启用
                </el-dropdown-item
                >
                <el-dropdown-item
                  v-else
                  @click.native="deBounceWrap(handleStatus, scope.row)"
                >启用
                </el-dropdown-item
                >
                <el-dropdown-item
                  @click.native="deBounceWrap(handleTask, scope.row)"
                >定时任务
                </el-dropdown-item
                >
                <el-dropdown-item
                  @click.native="deBounceWrap(handleSetTop, scope.row)"
                >置顶
                </el-dropdown-item
                >
                <el-dropdown-item
                  @click.native="deBounceWrap(handleDel, scope.row)"
                >删除
                </el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <cus-pagination
        :limit.sync="listQuery.page_size"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="getList"
      />
    </el-card>
    <!-- 新增编辑弹窗 -->
    <el-dialog
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="titleOptions[title]"
      :visible.sync="dialogVisible"
      width="40%"
      @close="handleClear"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="套装名称" prop="gift_name">
          <el-input
            v-model="form.gift_name"
            clearable
            placeholder="请输入套装名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="套装说明" prop="gift_desc">
          <el-input
            v-model="form.gift_desc"
            clearable
            placeholder="请输入套装说明"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="套装展示图片" label-width="120px" prop="picture">
          <el-upload
            :before-upload="handleBeforeUploadPicture"

            :http-request="customizeUpload"
            :on-success="handleSuccess"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img v-if="form.picture" :src="form.picture" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="销售状态" prop="sale_status">
          <el-radio v-model="form.sale_status" :label="1">上架</el-radio>
          <el-radio v-model="form.sale_status" :label="0">下架</el-radio>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number
            v-model="form.sort"
            clearable
            placeholder="请输入排序"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="套装内容">
          <div
            v-for="(item, index) in suitList"
            :key="index"
            :class="[index ? 'mt-2' : '']"
          >
            <el-select
              v-model="item.gift_id"
              clearable
              placeholder="请选择礼物"
            >
              <el-option
                v-for="item in giftList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                clearable
              ></el-option>
            </el-select>
            <br/>
            <el-radio v-model="item.is_rare" :label="1">设置稀有</el-radio>
            <el-radio v-model="item.is_rare" :label="0">不设置稀有</el-radio>
            <el-button
              v-if="index"
              icon="el-icon-delete"
              plain
              size="small"
              type="danger"
              @click.prevent="removePart(item)"
            >删除
            </el-button
            >
          </div>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-plus" size="small" @click="addPart"
          >新增
          </el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button plain type="primary" @click="handleClose">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit, 'form')"
        >提交
        </el-button
        >
      </div>
    </el-dialog>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""
      ><em style="font-style: normal; color: red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 详情弹框 -->
    <el-dialog :visible.sync="dialogDetailVisible" title="套装详情" width="30%">
      <div
        v-for="(item, index) in detailsGift"
        :key="index"
        class="flex flex-row flex-initial justify-start items-start mb-10"
      >
        <div class="details-left">{{ '礼物' + (index + 1) }}</div>
        <div class="details-right">
          <div class="giftname">
            <span class="giftnameWord">礼物名称:</span>
            <el-tag type="primary">{{ item.name }}</el-tag>
          </div>
          <div class="detailsImg">
            <span class="giftnameWord">礼物图片:</span
            ><img :src="item.picture" class="giftImg"/>
          </div>
          <div>
            <span class="giftnameWord">是否稀有:</span>
            <el-tag v-if="item.is_rare === 1" type="success">是</el-tag>
            <el-tag v-if="item.is_rare === 0" type="danger">否</el-tag>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 定时任务 -->
    <el-dialog
      :before-close="handleTaskClose"
      :close-on-click-modal="false"
      :visible.sync="TaskVisible"
      title="设置定时任务"
      width="30%"
      @close="handleTaskClear"
    >
      <el-form
        ref="Taskform"
        :model="Taskform"
        :rules="Taskrules"
        label-width="120px"
      >
        <el-form-item label="操作" prop="action">
          <el-radio v-model="Taskform.action" :label="1">上架</el-radio>
          <el-radio v-model="Taskform.action" :label="0">下架</el-radio>
        </el-form-item>
        <el-form-item label="定时时间" prop="set_time">
          <el-date-picker
            v-model="Taskform.set_time"
            placeholder="选择定时时间"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button plain type="primary" @click="handleTaskClose"
        >返回
        </el-button
        >
        <el-button
          type="primary"
          @click="deBounceWrap(handleTaskSumbit, 'form')"
        >提交
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>


import {
  addGiftList,
  delGiftList,
  editGiftList,
  editStatus,
  getListApi,
  giftAll,
  giftDetails,
  setTop,
  shelfTask
} from '@/api/roomGift/limitedManagement'

export default {
  data() {
    return {

      data: [],
      listQuery: {
        sale_status: undefined,
        gift_name: undefined,
        page: 1,
        page_size: 10
      },
      total: 0,
      titleOptions: {
        add: '新增',
        edit: '编辑'
      },
      title: 'add',
      rowData: {},
      giftList: [],
      form: {
        gift_name: undefined,
        picture: undefined,
        sort: undefined,
        gift_desc: undefined,
        join_gift_info: [
          {
            gift_id: undefined,
            is_rare: undefined
          }
        ],
        sale_status: undefined
      },
      suitList: [{ gift_id: undefined, is_rare: undefined }],
      rules: {
        gift_name: [
          { required: true, message: '请输入套装名称', trigger: 'blur' }
        ],
        picture: [
          { required: true, message: '请上传套装展示图片', trigger: 'change' }
        ],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        gift_id: [{ required: true, message: '请选择套装', trigger: 'change' }],
        gift_desc: [
          { required: true, message: '请输入套装说明', trigger: 'blur' },
          { max: 100, message: '套装说明不能超过100个字符' }
        ],
        sale_status: [
          { required: true, message: '请选择套装状态', trigger: 'change' }
        ],
        is_rare: [
          { required: true, message: '请选择稀有状态', trigger: 'change' }
        ]
      },
      dialogVisible: false,
      //删除
      deleteDialogVisible: false,
      //勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',
      //当前的id
      currentId: '',
      //详情弹窗
      dialogDetailVisible: false,
      detailsGift: [],
      //设置定时上下架弹窗
      TaskVisible: false,
      Taskform: {
        action: undefined,
        set_time: undefined
      },
      Taskrules: {
        action: [{ required: true, message: '请选择操作', trigger: 'change' }],
        set_time: [
          { required: true, message: '请选择定时时间', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getGiftList()
  },
  methods: {
    //列表
    getList() {
      let data = JSON.parse(JSON.stringify(this.listQuery))
      if (!this.listQuery.sale_status) {
        data.sale_status = -1
      }
      getListApi(data).then(res => {
        this.data = res.data.data
        this.total = res.data.total
      })
    },
    //获取所有礼物
    getGiftList() {
      giftAll().then(res => {
        this.giftList = res.data
      })
    },
    handleSuccess() {
      this.form.picture = this.ossLastImgUrl
    },
    handleBeforeUploadPicture(file) {
      const isPic =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/webp'

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPic) {
        this.$message.error('请上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPic && isLt2M
    },
    //弹窗中增加
    addPart() {
      this.suitList.push({
        gift_id: undefined,
        is_rare: undefined
      })
    },
    //弹窗中删除
    removePart(item) {
      let index = this.suitList.indexOf(item)
      if (index !== -1) {
        this.suitList.splice(index, 1)
      }
    },
    //新增
    handleAdd() {
      this.title = 'add'
      this.dialogVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.title = 'edit'
      this.rowData = row

      this.suitList = []

      this.form.gift_name = this.rowData.name
      this.form.picture = this.rowData.picture
      this.form.sort = this.rowData.sort

      if (this.rowData.sold === 1) {
        this.form.sale_status = this.rowData.sold
      } else {
        this.form.sale_status = 0
      }
      this.form.gift_desc = this.rowData.desc

      giftDetails({ id: this.rowData.id }).then(res => {
        res.data.suit_gifts.forEach(item => {
          this.suitList.push({ gift_id: item.id, is_rare: item.is_rare })
          this.form.join_gift_info = this.suitList
        })
        this.dialogVisible = true
      })
    },
    handleSumbit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title === 'add') {
            let data = {
              gift_name: this.form.gift_name,
              picture: this.form.picture,
              sort: this.form.sort,
              gift_desc: this.form.gift_desc,
              sale_status: this.form.sale_status
            }
            let arr = []
            this.suitList.forEach(item => {
              arr.push({ gift_id: item.gift_id, is_rare: item.is_rare })
            })
            data.join_gift_info = JSON.stringify(arr)

            addGiftList(data).then(res => {
              if (res.code === 200) {
                this.$message.success('提交成功')
                this.getList()
                this.dialogVisible = false
              } else {
              }
            })
          }
          if (this.title === 'edit') {
            let data = {
              id: this.rowData.id,
              gift_name: this.form.gift_name,
              picture: this.form.picture,
              sort: this.form.sort,
              gift_desc: this.form.gift_desc,
              sale_status: this.form.sale_status
            }
            let arr = []
            this.suitList.forEach(item => {
              arr.push({ gift_id: item.gift_id, is_rare: item.is_rare })
            })
            data.join_gift_info = JSON.stringify(arr)

            editGiftList(data).then(res => {
              if (res.code === 200) {
                this.$message.success('编辑成功')
                this.getList()
                this.dialogVisible = false
              }
            })
          }
        } else {

          return false
        }
      })
    },
    //清空表单
    handleClose() {
      this.dialogVisible = false
    },
    handleClear() {
      this.$refs['form'].resetFields()
      this.form = {
        gift_name: undefined,
        picture: undefined,
        sort: undefined,
        gift_desc: undefined,
        gift_id: undefined,
        is_rare: undefined,
        sale_status: undefined
      }
      this.suitList = [
        {
          gift_id: undefined,
          is_rare: undefined
        }
      ]
    },
    //批量选中
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //批量删除
    handleDelAll() {
      if (this.multipleSelection.length) {
        /* 存在勾选数据 */
        const ids = this.multipleSelection.reduce(
          (pre, currRow) => {
            pre += `${currRow.id},`
            return pre
          },
          ''
        )
        delGiftList({ ids })
          .then(() => this.$message.success('删除成功！'))
          .catch(console.error)
          .finally(() => /* 刷新数据 */ {
            this.multipleSelection = []
            this.getList()
          })
      } /* 不存在勾选数据 */ else {
        this.$message.warning('请勾选要删除的数据！')
      }
    },
    // 删除
    handleDel(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      delGiftList(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功'
          })
        }
      })
    },
    //修改状态
    handleStatus(row) {
      this.currentId = row.id

      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('p', null, [h('span', null, '是否要改变当前礼物的状态？ ')]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            editStatus({ id: this.currentId }).then(res => {

              this.getList()
            })
            done()
          } else {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
            done()
          }
        }
      })
        .then(action => {

          this.$message({
            type: 'success',
            message: '操作成功'
          })
        })
        .catch(res => res)
    },
    //置顶
    handleSetTop(row) {
      this.currentId = row.id

      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('p', null, [h('span', null, '是否要将该条数据置顶？ ')]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            setTop({ id: this.currentId }).then(res => {

              this.getList()
            })
            done()
          } else {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
            done()
          }
        }
      })
        .then(action => {

          this.$message({
            type: 'success',
            message: '操作成功'
          })
        })
        .catch(res => res)
    },
    //详情
    handleDetails(row) {
      this.currentId = row.id
      this.dialogDetailVisible = true
      giftDetails({ id: this.currentId }).then(res => {
        this.detailsGift = res.data.suit_gifts
      })
    },
    //设置定时任务
    handleTask(row) {
      this.currentId = row.id
      this.TaskVisible = true
    },
    //关闭定时任务弹窗
    handleTaskClear() {
      this.TaskVisible = false
      this.$refs['Taskform'].resetFields()
      this.Taskform = {
        action: undefined,
        set_time: undefined
      }
    },
    handleTaskClose() {
      this.$refs['Taskform'].resetFields()
      this.Taskform = {
        action: undefined,
        set_time: undefined
      }
      this.TaskVisible = false
    },
    handleTaskSumbit() {
      this.$refs['Taskform'].validate(valid => {
        if (valid) {
          let data = {
            id: this.currentId,
            action: this.Taskform.action,
            set_time: this.Taskform.set_time
          }
          shelfTask(data).then(res => {
            if (res.code === 200) {
              this.$message.success('提交成功')
              this.getList()
              this.TaskVisible = false
            }
          })
        } else {

          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}

/deep/ .el-upload-list__item {
  transition : none !important;
}

/deep/ .el-upload-list--picture {
  max-height : 103px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list--text {
  max-height : 100px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list__item-name {
  white-space : normal !important;
}

.details-left {
  width       : 120px;
  font-size   : 16px;
  font-weight : 700;
  margin-left : 20px;
  margin-top  : 2px;
}

.details-right {
  .giftname {
    margin-bottom : 20px;
  }

  .detailsImg {
    display        : flex;
    flex-direction : row;
    margin-bottom  : 20px;

    .giftImg {
      width  : 150px;
      height : 150px;
      border : 1px dashed rgba(177, 175, 175, 0.657);
    }
  }

  .giftnameWord {
    font-size     : 14px;
    font-weight   : 700;
    padding-right : 10px;
  }
}
</style>
